/*
 * @Author: yangzonglong
 * @Date: 2021-07-28 14:33:50
 * @version: v1.0.0
 * @Descripttion: 导入json
 * @LastEditors: yangzonglong
 * @LastEditTime: 2021-07-28 16:15:49
 * @Auditor: 
 */
import React, { useRef } from 'react';
import { Menu } from 'antd';
import roleAuth from '@library/utils/routePermit/routePermit';

const inputStyle: React.CSSProperties = {
  opacity: 0,
  width: 0
};

interface IProps {
  onOk(str: string): void;
}

const ImportJson = ({ onOk }: IProps) => {
  const inputRef = useRef<HTMLInputElement>(null);

  const roleAuthValue = roleAuth();

  const openFile = () => inputRef.current?.click();

  const onChange = (e: React.BaseSyntheticEvent) => {
    const files = e.target.files;
    const file = files?.[0];

    if (file) {
      const reader = new FileReader();
      reader.readAsText(file);

      reader.onload = (result) => {
        const str = result.target?.result;
        if (str) onOk(str as string);
      };
    }
  };

  return (
    <>
      <Menu>
        {roleAuthValue.edit && <Menu.Item key='import' onClick={openFile}>{window.$app.t('import')}</Menu.Item>}
      </Menu>
      <input onChange={onChange} ref={inputRef} style={inputStyle} type='file' accept='.json' />
    </>
  );
};

export default ImportJson;